﻿using Newtonsoft.Json.Linq;
using System;
using up7.db.model;
using up7.db.sql;
using up7.db.utils;
using up7.filemgr.app;

namespace up7.api.filemgr
{
    public partial class search : WebBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string uid = this.reqStr("uid");
            var pid = this.reqStr("pid");
            var pathRel = this.reqStrDecode("pathRel");
            if (!pathRel.EndsWith("/")) pathRel += '/';
            bool isRootDir = pathRel == "/";
            var key = this.reqStrDecode("key");

            string pathRelSql = string.Format("f_pathRel='{0}'+f_nameLoc", pathRel);
            string keySql = string.Format("f_nameLoc like '%{0}%'", key);

            var tp = ConfigReader.dbType();
            if (tp == DataBaseType.Oracle || tp == DataBaseType.ODBC || tp == DataBaseType.Kingbase)
            {
                pathRelSql = string.Format("f_pathRel=CONCAT('{0}',f_nameLoc)", pathRel);
                keySql = string.Format("f_nameLoc like '%%{0}%%'", key);
            }
            if (isRootDir) pathRelSql = "";

            //文件表
            var files = SqlTable.build("up7_files").reads<FileInf>(
                "f_id,f_pid,f_nameLoc,f_sizeLoc,f_lenLoc,f_time,f_pidRoot,f_fdTask,f_pathSvr,f_pathRel,f_object_key",
                SqlWhere.build()
                .eq("f_complete", true)
                .eq("f_deleted", false)
                .eq("f_uid", uid)
                .sql("f_pathRel", pathRelSql)
                .sql("f_nameLoc", keySql),
                SqlSort.build().desc("f_fdTask").desc("f_time"));

            //目录表
            var folders = SqlTable.build("up7_folders").reads<FileInf>(
                "f_id,f_nameLoc,f_pid,f_sizeLoc,f_time,f_pidRoot,f_pathRel",
                SqlWhere.build()
                .eq("f_complete", true)
                .eq("f_deleted", false)
                .eq("f_uid", uid)
                .sql("f_pathRel", pathRelSql)
                .sql("f_nameLoc", keySql),
                SqlSort.build().desc("f_time"));

            foreach (var fd in folders)
            {
                fd.fdTask = true;
                fd.fdChild = false;
                files.Add(fd);
            }

            JObject o = new JObject();
            o["count"] = folders.Count;
            o["code"] = 0;
            o["msg"] = string.Empty;
            o["data"] = JToken.FromObject(files);

            this.toContent(o);
        }
    }
}